/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.uca.sisbec.actions.gastos;

import com.uca.sisbec.beans.NameAndCarnetBean;
import com.uca.sisbec.commons.HibernateAction;
import com.uca.sisbec.forms.gastos.GastosForm;
import com.uca.sisbec.helpers.gastos.GastosHelper;
import com.uca.sisbec.helpers.gastos.PresupuestoHelper;
import com.uca.sisbec.helpers.manto.BecarioHelper;
import com.uca.sisbec.mapping.Gasto;
import com.uca.sisbec.mapping.GastoXBecario;
import com.uca.sisbec.mapping.Usuario;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;

/**
 *
 * @author Alex
 */
public class GastosAction extends HibernateAction {
    
    public ActionForward init(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        PresupuestoHelper ph = new PresupuestoHelper(getSession(request));
        if(ph.ExistePresupuestoMesActual()){
            request.setAttribute("extra", "yes");
        } else {
            request.setAttribute("extra", "no");
        }
        request.setAttribute("save", "new");
        form.reset(mapping, request);
        BecarioHelper bh = new BecarioHelper(getSession(request));
        request.setAttribute("becarios", bh.getNamesAndCarnets());
        return mapping.findForward("success");
    }
    
    public ActionForward initBusqueda(ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        return mapping.findForward("search");
    }
        
    public ActionForward RegistrarGasto(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        PresupuestoHelper ph = new PresupuestoHelper(getSession(request));
        if(ph.ExistePresupuestoMesActual()){
            request.setAttribute("extra", "yes");
        } else {
            request.setAttribute("extra", "no");
        }
        
        ActionMessages msg = new ActionMessages();
        ActionErrors errors = new ActionErrors();
        BecarioHelper bh = new BecarioHelper(getSession(request));   
        GastosForm gf = (GastosForm) form;
        
        switch(validarForm(gf)){
            
            case 0: break;
                
            case 1: errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("gasto.invalido"));
                    request.setAttribute("errors", errors);
                    request.setAttribute("becarios", bh.getNamesAndCarnets());
                    request.setAttribute("save", "new");
                    return mapping.findForward("success");
                
            case 2: errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("concepto.vacio"));
                    request.setAttribute("errors", errors);
                    request.setAttribute("becarios", bh.getNamesAndCarnets());
                    request.setAttribute("save", "new");
                    return mapping.findForward("success");                    
                    
                
            case 3: errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("becarios.noseleccionados"));
                    request.setAttribute("errors", errors);
                    request.setAttribute("becarios", bh.getNamesAndCarnets());
                    request.setAttribute("save", "new");
                    return mapping.findForward("success");
                    
        }
        
        
        if(gf.getRecIndiv() == 1) {
            //Generar recibos individuales
            gf.setCantBecBenef(1);
            GastosHelper gh = new GastosHelper(getSession(request));
            String becarios = gf.getTokens();
            StringTokenizer carnetsGroup = new StringTokenizer(becarios, "|");
            String carnet = "";
            List<NameAndCarnetBean> becariosBenef = new ArrayList<NameAndCarnetBean>();
            int idGasto = 0;
            while(carnetsGroup.hasMoreTokens()) {
                String tkn = carnetsGroup.nextToken();
                NameAndCarnetBean tknBean = new NameAndCarnetBean(tkn);
                becariosBenef.add(tknBean);
                idGasto = gh.RegistrarGasto(gf, GetUsuario(request));
                getSession(request).flush();
                carnet = tkn.split("-")[0].trim();
                gh.RegistrarGastoXBecario(idGasto, carnet);
                getSession(request).flush();
            }
            List<NameAndCarnetBean> becariosList = bh.getNamesAndCarnets();
            for(int i = 0; i < becariosBenef.size(); i++) {
                for(int j = 0; j < becariosList.size(); j++) {
                    if(becariosBenef.get(i).getNameAndCarnet().equals(becariosList.get(j).getNameAndCarnet()))
                        becariosList.remove(j);
                }
            }
            request.setAttribute("becarios", becariosList);
            request.setAttribute("becariosBenef", becariosBenef);
            msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("gasto.nuevo"));
            request.setAttribute("msg", msg);
            request.setAttribute("save", "update"); 
        } else {
            //Generar un solo recibo
            GastosHelper gh = new GastosHelper(getSession(request));
            int idGasto = gh.RegistrarGasto(gf, GetUsuario(request));
            gf.setIdGasto(idGasto);
            getSession(request).flush();
            String becarios = gf.getTokens();
            StringTokenizer carnetsGroup = new StringTokenizer(becarios, "|");
            String carnet = "";
            List<NameAndCarnetBean> becariosBenef = new ArrayList<NameAndCarnetBean>();
            while(carnetsGroup.hasMoreTokens()) {
                String tkn = carnetsGroup.nextToken();
                NameAndCarnetBean tknBean = new NameAndCarnetBean(tkn);
                becariosBenef.add(tknBean);
                carnet = tkn.split("-")[0].trim();
                gh.RegistrarGastoXBecario(idGasto, carnet);
                getSession(request).flush();
            }
            List<NameAndCarnetBean> becariosList = bh.getNamesAndCarnets();
            for(int i = 0; i < becariosBenef.size(); i++) {
                for(int j = 0; j < becariosList.size(); j++) {
                    if(becariosBenef.get(i).getNameAndCarnet().equals(becariosList.get(j).getNameAndCarnet()))
                        becariosList.remove(j);
                }
            }
            request.setAttribute("becarios", becariosList);
            request.setAttribute("becariosBenef", becariosBenef);
            msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("gasto.nuevo"));
            request.setAttribute("msg", msg);
            request.setAttribute("save", "update"); 
        }
        return mapping.findForward("success");
    }
    
    
    private int validarForm(GastosForm form){
        if(form.getMonto() <= 0 || form.getMonto() > 999.99) {
            return 1;
        } else {
            if(form.getConcepto().trim().equals("")) {
                return 2;
            } else {
                if(form.getCantBecBenef() == 0) {
                    return 3;
                } else {
                    return 0;
                }
            }
        }
    }
    
    public ActionForward BuscarGasto(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        GastosHelper gh = new GastosHelper(getSession(request));
        GastosForm gf = (GastosForm) form;
        request.setAttribute("gastosData", gh.BuscarGastosDB(gf));
        return mapping.findForward("search");
    }
    
    public ActionForward SeleccionarGasto(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        GastosForm gf = (GastosForm) form;
        GastosHelper gh = new GastosHelper(getSession(request));
        Gasto gasto = gh.BuscarGastoDB(gf.getIdGasto(), gf);
        request.setAttribute("save", "update");
        
        PresupuestoHelper ph = new PresupuestoHelper(getSession(request));
        if(ph.ExistePresupuestoMesActual()){
            request.setAttribute("extra", "yes");
        } else {
            request.setAttribute("extra", "no");
        }
        
        BecarioHelper bh = new BecarioHelper(getSession(request));
        List<NameAndCarnetBean> becariosList = bh.getNamesAndCarnets();
        
        List<NameAndCarnetBean> becariosBenef = new ArrayList<NameAndCarnetBean>();
        
        List<GastoXBecario> gxb = new ArrayList<GastoXBecario>(gasto.getGastoXBecarios());
                       
        for(int i = 0; i < gxb.size(); i++){
            for(int j = 0; j < becariosList.size(); j++){
                String nameandcarnet = gxb.get(i).getBecario().getCarnet() + " - " + gxb.get(i).getBecario().getNombres() + " " + gxb.get(i).getBecario().getApellidos();
                if(nameandcarnet.equals(becariosList.get(j).getNameAndCarnet())) {
                    becariosBenef.add(new NameAndCarnetBean(nameandcarnet));
                }
            }
        }
        request.setAttribute("becariosBenef", becariosBenef);
        
        for(int i = 0; i < becariosBenef.size(); i++) {
            for(int j = 0; j < becariosList.size(); j++) {
                if(becariosBenef.get(i).getNameAndCarnet().equals(becariosList.get(j).getNameAndCarnet()))
                    becariosList.remove(j);
            }
        }
        
        request.setAttribute("becarios", becariosList);
        return mapping.findForward("success");
    }
    
    
    public ActionForward ModificarGasto(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        GastosForm gf = (GastosForm) form;
        GastosHelper gh = new GastosHelper(getSession(request));
        ActionErrors errors = new ActionErrors();
        if(gf.getMonto() <= 0 || gf.getMonto() > 999.99){
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("gasto.invalido"));
            request.setAttribute("errors", errors);
        } else {
            if(gf.getJustificacion().trim().equals("")) {
                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("justificacion.vacia"));
                request.setAttribute("errors", errors);
            } else {
                if(gf.getEstado().equals("N/A")) {
                    errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("estado.noseleccionado"));
                    request.setAttribute("errors", errors);
                } else {
                    gh.ModificarGastoDB(gf, GetUsuario(request));
                    ActionMessages msg = new ActionMessages();
                    msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("gasto.modificado"));
                    request.setAttribute("msg", msg);
                    request.setAttribute("save", "new");
                }
            }
        }
              
        PresupuestoHelper ph = new PresupuestoHelper(getSession(request));
        if(ph.ExistePresupuestoMesActual()){
            request.setAttribute("extra", "yes");
        } else {
            request.setAttribute("extra", "no");
        }
        
        gf.reset(mapping, request);
        BecarioHelper bh = new BecarioHelper(getSession(request));
        request.setAttribute("becarios", bh.getNamesAndCarnets());
        return mapping.findForward("success");
    }
    
    private String GetUsuario(HttpServletRequest request){
        Usuario u = (Usuario) request.getSession().getAttribute(_USER);
        return u.getAlias();
    }
    
}
